package wwj.controller;

import com.sun.net.httpserver.HttpServer;
import wwj.bean.User;
import wwj.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/enroll")
public class EnrollServlet extends HttpServlet {
    LoginService loginService = new LoginService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        String tel = req.getParameter("tel");
        Boolean flag = loginService.checkUsr(username);
        System.out.println("用户名检测："+flag);
        if (gender==null){
            req.setAttribute("radio","单选框不能为空");
            req.getRequestDispatcher("enroll.jsp").forward(req,resp);
        }
        if (!flag){
            resp.getWriter().write("用户名已经存在");
            resp.setHeader("refresh","2;enroll.jsp");
        }else {
            User user = new User();
            user.setUsr(username);
            user.setPwd(password);
            user.setEmail(email);
            user.setSex(gender);
            user.setTel(tel);

            String enroll_status = loginService.enroll(user);
            System.out.println("注册状态："+enroll_status);

            if ("系统错误".equals(enroll_status)) {
                resp.getWriter().write(enroll_status+"  3秒后将自动跳转");
                resp.setHeader("refresh","3;enroll.jsp");
            } else if ("注册成功".equals(enroll_status)) {
                resp.getWriter().write(enroll_status+"  3秒后将自动跳转");
                resp.setHeader("refresh","3;login.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
